<template>
  <div>
    <el-form :inline="true">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="编号">
            <el-input v-model="queryParam.Code" @keyup.enter.native="research" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="名称">
            <el-input v-model="queryParam.Name" @keyup.enter.native="research" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row style="text-align: center">
        <el-button type="warning" round @click="research">
          查询
        </el-button>
      </el-row>
    </el-form>

    <el-row style="margin-top: 20px">
      <el-button type="primary" @click="toAdd">
        添加
      </el-button>
      <el-button type="primary" @click="toExport">
        导出
      </el-button>
      <el-button :disabled="!multipleSelection || multipleSelection.length===0" type="primary" @click="exportApiMd">
        导出API-MD文档
      </el-button>
    </el-row>

    <el-table
      :data="data"
      size="small"
      :height="tableHeight"
      border
      fit
      highlight-current-row
      style="width: 100%; margin-top: 20px"
      @sort-change="sortChange"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
      />
      <el-table-column width="300" sortable="custom" label="名称" prop="Name" />
      <el-table-column width="300" sortable="custom" label="编号" prop="Code" />
      <el-table-column label="类型" width="100">
        <template slot-scope="scope">
          {{ scope.row.Type | dictFilter(enums.reportTypeEnum) }}
        </template>
      </el-table-column>
      <el-table-column sortable="custom" prop="CreatedAt" label="创建时间" width="100">
        <template slot-scope="scope">
          {{ scope.row.CreatedAt | parseDate }}
        </template>
      </el-table-column>
      <el-table-column sortable="custom" prop="UpdatedAt" label="修改时间" width="100">
        <template slot-scope="scope">
          {{ scope.row.UpdatedAt | parseDate }}
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right">
        <template slot-scope="scope">
          <el-button type="text" @click="toEdit(scope.row)">
            修改
          </el-button>
          <el-button
            v-if="scope.row.Type === enums.reportTypeEnum.SQL.value"
            type="text"
            @click="editForm(scope.row)"
          >
            编辑表单
          </el-button>
          <el-button
            v-if="scope.row.Type === enums.reportTypeEnum.SQL.value"
            type="text"
            @click="toEditSql(scope.row)"
          >
            编辑SQL
          </el-button>
          <el-button
            v-if="scope.row.Type === enums.reportTypeEnum.SQL.value"
            type="text"
            @click="toEditReturn(scope.row)"
          >
            编辑返回信息
          </el-button>
          <el-button
            v-if="scope.row.Type === enums.reportTypeEnum.AGGREGATION.value"
            type="text"
            @click="toEditAggregate(scope.row)"
          >
            编辑聚合信息
          </el-button>
          <el-button type="text" @click="toTest(scope.row)">
            测试
          </el-button>
          <el-button type="text" @click="toCopy(scope.row)">
            复制
          </el-button>
          <el-button type="text" @click="toDel(scope.row)">
            废弃
          </el-button>
          <el-button type="text" @click="toShowApi(scope.row)">
            API文档
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-row style="margin-top: 10px">
      <el-col :span="24">
        <el-pagination
          v-show="TotalRecord>0"
          :current-page="queryParam.CurrentPage"
          :page-sizes="[10,20,30, 50, 500]"
          :page-size="queryParam.PageSize"
          :total="TotalRecord"
          background
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-col>
    </el-row>
  </div>
</template>

<script>
import reportApi from '@/api/report'
import reportStatusEnum from '@/enums/report/reportStatusEnum'
import reportTypeEnum from '@/enums/report/reportTypeEnum'
import apolloClient from '@/utils/graphql'
import gql from 'graphql-tag'
import { saveAs } from 'file-saver'
export default {
  name: 'ReportList',
  data() {
    return {
      queryParam: {
        CurrentPage: 1,
        PageSize: 10,
        Code: null,
        Name: null,
        OrderBy: '',
        OrderColumn: ''
      },
      data: [],
      TotalRecord: 0,
      currentRow: '',
      enums: {
        reportStatusEnum,
        reportTypeEnum
      },
      multipleSelection: []
    }
  },

  computed: {
    // 返回当前列的数据
    currentData() {
      if (this.currentRow === '' || this.currentRow === undefined || this.currentRow == null) {
        return {}
      }
      return this.data[this.currentRow]
    },
    tableHeight() {
      return document.body.clientHeight - 300
    }
  },
  mounted() {
    var token = this.$route.query['token']
    this.$store.dispatch('user/storeToken', token || '')
  },
  activated() {
    this.search()
  },
  methods: {
    sortChange(column) {
      this.queryParam.OrderBy = column.order
      this.queryParam.OrderColumn = column.prop
      this.research()
    },
    // 处理选择的变化
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    toAdd() {
      this.$router.push(`/report/add`)
    },
    toExport() {

    },
    exportApiMd() {
      var ids = []
      for (const multipleSelectionElement of this.multipleSelection) {
        ids.push(multipleSelectionElement.ReportId)
      }
      apolloClient.query({
        query: gql`query ($ids:[String!]!){
                exportApiMarkdown(ids: $ids)
}`, variables: { ids }
      }).then(response => {
        if (response.data && response.data.exportApiMarkdown) {
          saveAs(new Blob([response.data.exportApiMarkdown], {
            type: 'text/plain;charset=utf-8'
          }), 'api.md')
        }
      })
    },
    s2ab(s) {
      var buf = new ArrayBuffer(s.length)
      var view = new Uint8Array(buf)
      for (var i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF
      return buf
    },
    toShowApi(row) {
      this.$router.push(`report/apidoc/${row.ReportId}`)
    },
    toEdit(row) {
      this.$router.push(`/report/edit/${row.ReportId}`)
    },
    editForm(row) {
      this.$router.push(`/report/editForm/${row.ReportId}`)
    },
    toEditSql(row) {
      this.$router.push(`/report/editSql/${row.ReportId}`)
    },
    toEditReturn(row) {
      this.$router.push(`/report/editResult/${row.ReportId}`)
    },
    toEditAggregate(row) {
      this.$router.push(`/report/editAggregate/${row.ReportId}`)
    },
    toTest(row) {
      this.$router.push(`/report/test/json/${row.Code}`)
    },
    toCopy(row) {
      this.$prompt('请输入新的编号', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        apolloClient.mutate({
          mutation: gql`mutation($data:CopyReportReq!){
                    copyReport(Req:  $data)
                }`,
          variables: { data: { ReportId: row.ReportId, Code: value }}
        }).then(response => {
          if (response.data) {
            this.$notify.success('操作成功')
            this.research()
          } else {
            this.$notify.error(response.errors[0].message)
          }
        }).catch((err) => {
          this.$notify.error(err.message)
        })
      })
    },
    toDel(row) {
      this.$confirm('确定废弃?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        apolloClient.mutate({
          mutation: gql`mutation($unionId:String!){
                    dismissReport(ReportId:  $unionId)
                }`,
          variables: { unionId: row.ReportId }
        }).then(response => {
          if (response.data) {
            this.$notify.success('操作成功')
            this.research()
          } else {
            this.$notify.error(response.errors[0].message)
          }
        }).catch((err) => {
          this.$notify.error(err.message)
        })
      })
    },
    enableReport(row) {
      reportApi.enableReport(row.ReportId).then(response => {
        if (response.data) {
          this.$notify.success('操作成功')
          this.research()
        }
      })
    },
    dismissReport(row) {
      reportApi.dismissReport(row.ReportId).then(response => {
        if (response.data) {
          this.$notify.success('操作成功')
          this.research()
        }
      })
    },
    search() {
      reportApi.getReportList(this.queryParam).then(response => {
        console.log(response)
        var responseData = response.data
        this.data = responseData.reportPage.Records
        this.TotalRecord = responseData.reportPage.TotalRecord
      })
    },

    // 处理每页大小改变
    handleSizeChange(val) {
      this.queryParam.PageSize = val
      this.search()
    },
    // 处理页数改变
    handleCurrentChange(val) {
      this.queryParam.CurrentPage = val
      this.search()
    },
    // 重置分页条件，发起查询
    research() {
      this.queryParam.CurrentPage = 1
      this.search()
    }

  }
}
</script>

<style>
#app {
    font-family: 'Avenir', Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-align: center;
    color: #2c3e50;
    margin-top: 60px;
}
</style>
